package com.ruoyi.interview.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtils;
import com.ruoyi.interview.domain.IntervInfo;
import com.ruoyi.interview.domain.IntervPostinv;
import com.ruoyi.interview.domain.IntervWay;
import com.ruoyi.interview.domain.vo.IntervInfoVo;
import com.ruoyi.interview.mapper.IntervInfoMapper;
import com.ruoyi.interview.service.IIntervInfoService;
import com.ruoyi.interview.service.IIntervPostinvService;
import com.ruoyi.interview.service.IIntervWayService;
import com.ruoyi.interview.tool.JudgeNullUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Service业务层处理
 *
 */
@Service
public class IntervInfoServiceImpl implements IIntervInfoService
{
    @Resource
    private IntervInfoMapper intervInfoMapper;

    @Autowired
    private IIntervPostinvService postinvService;
    @Autowired
    private IIntervWayService wayService;


    /**
     * 查询
     *
     * @param id 主键
     * @return
     */
    @Override
    public IntervInfoVo selectIntervInfoById(Long id)
    {
        IntervInfo intervInfo = intervInfoMapper.selectIntervInfoById(id);
        //拷贝成vo
        IntervInfoVo intervInfoVo = BeanCopyUtils.copyBean(intervInfo, IntervInfoVo.class);
        //封装vo
        intervInfoVo.setWay(wayService.selectIntervWayByWId(intervInfo.getwId()).getWay());
        intervInfoVo.setPName(postinvService.selectIntervPostinvByPId(intervInfo.getpId()).getpName());
        return intervInfoVo;

    }

    /**
     * 查询列表
     *
     * @param
     * @return
     * 完成功能：按条件查询，我才用的是非联表查询，略显冗余
     * todo 待优化
     *
     */
    @Override
    public List<IntervInfoVo> selectIntervInfoList(IntervInfoVo intervInfoVo)
    {   //ps此功能多表分别查询可以改成连表，我直接封装返回的，不想多表联查
        //封装info
        IntervInfo intervInfo = BeanCopyUtils.copyBean(intervInfoVo, IntervInfo.class);
        intervInfo.setpId(postinvService.selectPidByPName(intervInfoVo.getpName()));
        intervInfo.setwId(wayService.selectIdByWay(intervInfoVo.getWay()));
        //根据intervInfo查询
        List<IntervInfo> intervInfos = intervInfoMapper.selectIntervInfoList(intervInfo);
        List<IntervInfoVo> intervInfoVos = BeanCopyUtils.copyBeanList(intervInfos, IntervInfoVo.class);
        //封装pName和Way
        for (int i = 0; i < intervInfoVos.size(); i++) {

            intervInfoVos.get(i).
                    setPName(postinvService.
                            selectIntervPostinvByPId(intervInfos
                                    .get(i)
                                    .getpId())
                            .getpName());


                intervInfoVos.get(i).
                        setWay(wayService.
                                selectIntervWayByWId(intervInfos
                                        .get(i)
                                        .getwId())
                                .getWay());

        }
        //过滤，按照条件查找
        if (intervInfoVo.getpName()!=null){
            intervInfoVos = intervInfoVos.stream()
                    .filter(o -> o.getpName().equals(intervInfoVo.getpName())).collect(Collectors.toList());
        }
        if (intervInfoVo.getWay()!=null){
            intervInfoVos = intervInfoVos.stream()
                    .filter(o -> o.getWay().equals(intervInfoVo.getWay())).collect(Collectors.toList());
        }
        return intervInfoVos;
    }

    /**
     * 新增
     *
     * @param intervInfoVo
     * @return 结果
     */
    @Override
    public int insertIntervInfo(IntervInfoVo intervInfoVo)
    {
        /** 封装info */
        IntervInfo intervInfo = BeanCopyUtils.copyBean(intervInfoVo, IntervInfo.class);
        /** 设置创建时间 */
        intervInfo.setCreateTime(DateUtils.getNowDate());
        /** 设置创建者 */
        intervInfo.setCreateBy(SecurityUtils.getUsername());


        /** 如果创建的电话号与数据库里的电话号相同则返回手机号相同的错误信息*/
        if (intervInfoMapper.selectIntervInfoByPhone(intervInfoVo.getPhone())!=null){
            /** 返回给前端错误信息 */
            return 0;
        }else if (intervInfoMapper.selectIntervInfoByName(intervInfoVo.getInterviewee())!=null){
            /** 如果插入进来的姓名和数据库里的姓名相同则将插入的姓名后面生成4个随机数字 */
            intervInfo.setInterviewee(intervInfoVo.getInterviewee()+UUID.randomUUID().toString().substring(0,4));
        }

        intervInfo.setpId(JudgeNullUtil.ifNull(postinvService.selectPidByPName(intervInfoVo.getpName())));
        intervInfo.setwId( JudgeNullUtil.ifNull(wayService.selectIdByWay(intervInfoVo.getWay())));
        return intervInfoMapper.insertIntervInfo(intervInfo);
    }

    /**
     * 修改
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int updateIntervInfo(IntervInfoVo intervInfoVo)
    {
        IntervInfo intervInfo = BeanCopyUtils.copyBean(intervInfoVo, IntervInfo.class);
        intervInfo.setUpdateTime(DateUtils.getNowDate());
        /**设置修改人*/
        intervInfo.setUpdateBy(SecurityUtils.getUsername());
        intervInfo.setpId(JudgeNullUtil.ifNull(postinvService.selectPidByPName(intervInfoVo.getpName())));
        intervInfo.setwId( JudgeNullUtil.ifNull(wayService.selectIdByWay(intervInfoVo.getWay())));
        return intervInfoMapper.updateIntervInfo(intervInfo);
    }

    /**
     * 批量删除
     *
     * @param ids 需要删除的主键
     * @return 结果
     */
    @Override
    public int deleteIntervInfoByIds(Long[] ids)
    {
        return intervInfoMapper.deleteIntervInfoByIds(ids);
    }

    /**
     * 删除信息
     *
     * @param id 主键
     * @return 结果
     */
    @Override
    public int deleteIntervInfoById(Long id)
    {
        return intervInfoMapper.deleteIntervInfoById(id);
    }

    @Override
    public int updateIntervPid(Long[] pid) {
        return intervInfoMapper.updateIntervInfoPid(pid);
    }

    @Override
    public int updateIntervWid(Long[] Wids) {
        return intervInfoMapper.updateIntervInfoWid(Wids);
    }

    @Override
    public String importUser(List<IntervInfoVo> infoVoList, Boolean updateSupport, String operName) {
        /** 导入数据不能为空 */
        if (StringUtils.isNull(infoVoList) || infoVoList.size() == 0)
        {
            throw new GlobalException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (IntervInfoVo infoVo : infoVoList)
        {
            try
            {   //去重功能
                // 根据电话验证是否存在这个用户
                // 考虑到重名几率可能有，所以
                IntervInfo info = intervInfoMapper.selectIntervInfoByName(infoVo.getInterviewee());
                IntervInfo infoByPhone = intervInfoMapper.selectIntervInfoByPhone(infoVo.getPhone());
                if (StringUtils.isNull(info)||info.getDelFlag()==0)
                {
                    info=new IntervInfo();
                    BeanUtils.copyProperties(infoVo,info);
                    info.setpId(postinvService.selectPidByPName(infoVo.getpName()));
                    info.setwId(wayService.selectIdByWay(infoVo.getWay()));
                    this.intervInfoMapper.insertIntervInfo(info);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "面试信息" + infoVo.getInterviewee() + " 导入成功");
                }else if (info.getInterviewee().equals(infoVo.getInterviewee())&&(!info.getPhone().equals(infoVo.getPhone())))
                {
                    BeanUtils.copyProperties(infoVo,info);
                    info.setPhone(infoVo.getPhone());
                    info.setInterviewee(infoVo.getInterviewee()+ UUID.randomUUID().toString().substring(0,8));
                    info.setpId(postinvService.selectPidByPName(infoVo.getpName()));
                    info.setwId(wayService.selectIdByWay(infoVo.getWay()));
                    this.intervInfoMapper.insertIntervInfo(info);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "面试信息" + infoVo.getInterviewee() + " 导入成功");
                }else if (updateSupport){
                    infoVo.setUpdateBy(operName);
                    info.setpId(postinvService.selectPidByPName(infoVo.getpName()));
                    info.setwId(wayService.selectIdByWay(infoVo.getWay()));
                    this.updateIntervInfo(infoVo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "面试信息 " + infoVo.getInterviewee() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "面试信息" + infoVo.getInterviewee() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "面试信息" + infoVo.getInterviewee() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    public List<String> selectInterviewwAll() {
        return intervInfoMapper.selectInterviewwAll();
    }
}
